<?php declare(strict_types=1);

namespace App\Services\Count;


use App\Models\Bi\Bill;
use App\Models\Model;
use App\Models\Store;
use App\Models\StoreAllPayWayList;
use App\Services\PrintSqlService;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;

class StoreCompanyCountService
{

    public function setWhere(Builder $query, array $where)
    {
        /**
         * "store_created_start_date" => $request->input("store_created_start_date"),
         * "store_created_end_date" => $request->input("store_created_end_date"),
         * "store_id" => $request->input("store_id"),
         * "user_id" => $userSubIds
         */
        if (!empty($where["store_created_start_date"])) {
            $query->where("stores.created_at", ">=", $where["store_created_start_date"]);
        }

        if (!empty($where["store_created_end_date"])) {
            $query->where("stores.created_at", "<=", $where["store_created_end_date"]);
        }
        if (!empty($where["store_id"])) {
            if (is_array($where["store_id"])) {
                $query->whereIn("stores.store_id", $where["store_id"]);
            } else {
                $query->where("stores.store_id", $where["store_id"]);
            }
        }
        if (!empty($where["user_id"])) {
            if (is_array($where["user_id"])) {
                $query->whereIn("stores.user_id", $where["user_id"]);
            } else {
                $query->where("stores.store_id", $where["store_id"]);
            }
        }
    }

    public function storeCompanyGroupCountList(array $where, bool $page = true): array
    {
//        PrintSqlService::listen();
//        $query = DB::connection("bi")->table("bills");
        $query = DB::table("stores")
            ->select([
                "stores.store_id",
                "store_pay_ways.company"
            ])
            ->leftJoin("store_pay_ways", "stores.store_id", "=", "store_pay_ways.store_id")
            ->where("stores.pid", 0)
            ->where("store_pay_ways.status", 1);
        $this->setWhere($query, $where);
        $query->groupBy(["stores.store_id", "store_pay_ways.company"]);
        $query->orderBy("stores.created_at", "desc");
        if ($page) {
            $total = Model::query()->fromSub($query, "tmp")->count();
            $list = $query->offset(($where["page"] - 1) * $where["pagesize"])->limit($where["pagesize"])->get()->toArray();
        } else {
            $total = 0;
            $list = $query->get()->toArray();
        }

        $storeIdArr = array_unique(array_column($list, "store_id"));

//        PrintSqlService::listen();
        $count = $this->biCount($storeIdArr);
        $stores = Store::query()->whereIn("store_id", $storeIdArr)->get()->toArray();

        $stores = array_combine(array_column($stores, "store_id"), $stores);
        $companys = StoreAllPayWayList::query()->get()->toArray();
        $companys = array_combine(array_column($companys, "company"), $companys);
        foreach ($list as $k => $v) {
            $v = (array)$v;
            $v["store_created_at"] = $stores[$v["store_id"]]["created_at"] ?? "";
            $v["store_name"] = $stores[$v["store_id"]]["store_name"] ?? "";
            $v["company_name"] = $companys[$v["company"]]["company_desc"] ?? "";
            $v["total_fee"] = $count[$v["store_id"]][$v["company"]]["total_fee"] ?? 0;
            $v["refund_fee"] = $count[$v["store_id"]][$v["company"]]["refund_fee"] ?? 0;
            $list[$k] = $v;
        }
        return [$total, $list];
    }

    protected function biCount(array $storeIdArr): array
    {
        $count = Bill::query()->select(["store_pid", "company",
            DB::raw("sum(total_fee) as total_fee"),
            DB::raw("sum(refund_fee) as refund_fee"),
        ])->whereIn("store_pid", $storeIdArr)
            ->groupBy(["store_pid", "company"])
            ->get()->toArray();

        $result = [];
        foreach ($count as $v) {
            $result[$v["store_pid"]][$v["company"]] = $v;
        }
        return $result;
    }


}